import axios from 'axios'

const apiClient = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  withCredentials: true,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  }
})

// 响应拦截器处理通用状态码
apiClient.interceptors.response.use(
  response => response,
  error => {
    const { status } = error.response
    
    switch (status) {
      case 401:
        console.error('Unauthorized - 需要登录')
        break
      case 403:
        console.error('Forbidden - 缺少权限')
        break
      case 422:
        console.error('Validation Error - 验证失败')
        break
      case 500:
        console.error('Server Error - 服务器错误')
        break
      default:
        console.error(`HTTP Error - ${status}`)
    }
    
    return Promise.reject(error)
  }
)

export const initCSRF = async () => {
  await apiClient.get('/csrf-cookie')
}

export default apiClient